package com.zjj.lbw.jdk.v7.unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author zhanglei.zjj
 * @description Unsafe操作数组下标示例 - ConcurrentHashMap源码中有用到
 * @date 2023/8/22 9:56
 */
public class TestUnsafe {
    private int i = 0;
    private static Unsafe UNFASE;
    private String[] table = {"1", "2", "3"};

    static {
        Field field = null;
        try {
            field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            UNFASE = (Unsafe) field.get(null);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        TestUnsafe obj = new TestUnsafe();

        // 数组中存储对象的对象头大小
        int ns = UNFASE.arrayIndexScale(String[].class);
        // 数组中第一个元素的起始位置
        int base = UNFASE.arrayBaseOffset(String[].class);
        // 获取对象实例的数组成员变量中的各个属性值，通过UNSAFE可以拿到内存中的最新值
        System.out.println(UNFASE.getObject(obj.table, base + 1 * ns));
    }
}
